package util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;

import org.apache.log4j.Logger;

import action.base.BaseAction;

//write by ssb
public class LoginFilter extends BaseAction implements Filter {

	protected Logger log = Logger.getLogger(this.getClass());

	public void destroy() {
		// super.getSession().remove("user");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			HttpServletRequest httprequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			String path = httprequest.getServletPath();

			if (!"/userAction!load.action".equals(path)) {
				if (!"/securityCodeImageAction.action".equals(path)) {
					HttpSession session = ((HttpServletRequest) request)
							.getSession();
					User user = (User) session.getAttribute("user");
					if (user == null) {
						if ("XMLHttpRequest".equalsIgnoreCase(httprequest
								.getHeader("x-requested-with"))) {
							httpResponse
									.setStatus(HttpServletResponse.SC_FORBIDDEN);
						} else {
							((HttpServletResponse) response)
									.sendRedirect(((HttpServletRequest) request)
											.getContextPath() + "/login.html");
						}
						return;
					}
				}
			}
			chain.doFilter(request, response);
		} catch (Exception e) {
			log.error("用户登录过滤", e);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
